package com.atguigu.lease.converter;

import com.atguigu.lease.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class BaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                if (StringUtils.isEmpty(source)){
                    return null;
                }
                for (T enumConstant : targetType.getEnumConstants()) {
                    if (enumConstant.getCode().toString().equals(source)){
                        return enumConstant;
                    }
                }
                throw new RuntimeException(source + "没有匹配的枚举对象");
            }

        };
    }
}
